<template>
  <div class="create-contest-page">
    <el-card class="create-card">
      <div class="title">创建比赛</div>
      <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
        <el-form-item label="竞赛名称" prop="title">
          <el-input v-model="form.title" placeholder="请输入竞赛名称" />
        </el-form-item>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="开始日期" prop="startTime">
              <el-date-picker v-model="form.startTime" type="date" value-format="YYYY-MM-DD" placeholder="选择开始日期" style="width:100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="截止日期" prop="endTime">
              <el-date-picker v-model="form.endTime" type="date" value-format="YYYY-MM-DD" placeholder="选择截止日期" style="width:100%" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-divider>题目列表</el-divider>
        <el-table
          :data="form.topics"
          border
          style="width: 100%; margin-bottom: 10px;"
          :header-cell-style="{ textAlign: 'center' }"
          :cell-style="{ textAlign: 'center', padding: '6px 0' }"
        >
          <el-table-column label="题目名称">
            <template #default="scope">
              <el-input v-model="scope.row.name" placeholder="如A/B/C" size="small" style="width: 90%;" />
            </template>
          </el-table-column>
          <el-table-column label="备注">
            <template #default="scope">
              <el-input v-model="scope.row.remark" placeholder="备注" size="small" style="width: 95%;" />
            </template>
          </el-table-column>
          <el-table-column label="上传文件">
            <template #default="scope">
              <el-upload
                :auto-upload="false"
                :show-file-list="true"
                :file-list="scope.row.fileList"
                :before-upload="file => beforeFileUpload(file)"
                :on-change="(file, fileList) => onFileChange(file, fileList, scope.$index)"
                accept=".pdf"
                :limit="1"
                style="display: inline-block;"
              >
                <el-button type="primary" size="small" style="width: 90px;">上传文件</el-button>
              </el-upload>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="100">
            <template #default="scope">
              <el-button type="danger" size="small" @click="removeTopic(scope.$index)" :disabled="form.topics.length <= 1">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-button type="primary" @click="addTopic">添加题目</el-button>
        <el-form-item>
          <el-button type="primary" @click="submitForm" :loading="loading">提交</el-button>
        </el-form-item>
      </el-form>
      <el-dialog v-model="dialogVisible" title="创建结果" width="400px" :close-on-click-modal="false">
        <div v-if="contestResult">
          <p>竞赛创建成功，竞赛ID：<b>{{ contestResult.contestId }}</b></p>
          <p>竞赛名称：<b>{{ contestResult.title }}</b></p>
        </div>
        <template #footer>
          <el-button type="primary" @click="dialogVisible = false">确定</el-button>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'

const formRef = ref(null)
const loading = ref(false)
const dialogVisible = ref(false)
const contestResult = ref(null)

const form = reactive({
  title: '',
  startTime: '',
  endTime: '',
  topics: [
    { name: '', remark: '', topicFile: null, fileList: [] }
  ]
})

const rules = {
  title: [{ required: true, message: '请输入竞赛名称', trigger: 'blur' }],
  startTime: [{ required: true, message: '请选择开始日期', trigger: 'change' }],
  endTime: [{ required: true, message: '请选择截止日期', trigger: 'change' }],
}

const addTopic = () => {
  form.topics.push({ name: '', remark: '', topicFile: null, fileList: [] })
}
const removeTopic = (idx) => {
  if (form.topics.length > 1) form.topics.splice(idx, 1)
}

const beforeFileUpload = (file) => {
  const isPDF = file.type === 'application/pdf'
  if (!isPDF) {
    ElMessage.error('仅支持PDF格式')
    return false
  }
  return true
}
const onFileChange = (file, fileList, idx) => {
     form.topics[idx].fileList = fileList.slice(-1)
     form.topics[idx].topicFile = file.raw
   }

const validateTopics = () => {
  for (let i = 0; i < form.topics.length; i++) {
    const t = form.topics[i]
    if (!t.name || !t.topicFile) {
      ElMessage.error(`请完整填写第${i + 1}题信息并上传PDF`)
      return false
    }
  }
  return true
}

const submitForm = () => {
  formRef.value.validate(async (valid) => {
    if (!valid) return
    if (!validateTopics()) return
    loading.value = true
    try {
      const formData = new FormData()
      formData.append('title', form.title)
      formData.append('startTime', form.startTime)
      formData.append('endTime', form.endTime)
      // topics: [{name, remark, topicFile}]
      form.topics.forEach((t, i) => {
        formData.append(`topics[${i}][name]`, t.name)
        formData.append(`topics[${i}][remark]`, t.remark)
        formData.append(`topics[${i}][topicFile]`, t.topicFile)
      })
      const token = localStorage.getItem('token')
      const res = await axios.post('/api/admin/contests', formData, {
        headers: {
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'multipart/form-data'
        }
      })
      if (res.data.code === 200) {
        contestResult.value = res.data.data
        dialogVisible.value = true
        ElMessage.success('竞赛创建成功')
        // 重置表单
        form.title = ''
        form.startTime = ''
        form.endTime = ''
        form.topics = [{ name: '', remark: '', topicFile: null, fileList: [] }]
      } else {
        ElMessage.error(res.data.message || '创建失败')
      }
    } catch (e) {
      ElMessage.error(e?.response?.data?.message || '创建失败')
    } finally {
      loading.value = false
    }
  })
}
</script>

<style scoped>
.create-contest-page {
  max-width: 800px;
  margin: 40px auto;
}
.create-card {
  padding: 32px 32px 24px 32px;
  border-radius: 10px;
  box-shadow: 0 2px 16px 0 rgba(60,90,150,0.08);
}
.title {
  font-size: 22px;
  font-weight: bold;
  margin-bottom: 24px;
  letter-spacing: 2px;
  color: #2d3a4b;
}
.topic-row {
  margin-bottom: 10px;
  background: #f8faff;
  padding: 10px 8px 2px 8px;
  border-radius: 6px;
  border: 1px solid #e0e6f1;
}
</style>
